//
//  SinaHomeViewController.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/12.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
import SDWebImage



class SinaHomeViewController: SinaBaseViewController {

    //cellID
    let cellID = "homeCellID"
    let retweeteCellID = "SinaHomeReTweeteCellID";
    
    //懒加载TableView
    lazy var tableView = UITableView()
    
    //懒加载菊花
    lazy var refreshIndicator: UIActivityIndicatorView? = {
        let refV = UIActivityIndicatorView()
        refV.activityIndicatorViewStyle = .gray
        return refV
    }()
    
    //懒加载提示lable
    lazy var refCountLbl = UILabel(frame: CGRect(x: 0, y: guideBarHeight - 35, width: screenWidth, height: 35))
    
    //懒加载自定义刷新控件
    lazy var refView = SinaRefreshView()
    
    //拥有一个homeViewModel
    lazy var homeViewModel = SinaHomeViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置访客界面
        visitorView.updateInfo(title: "点击回来,关注更多,哈哈哈哈哈哈哈哈哈哈哈哈吼吼😁哈", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
        
        addDemoBtn()
        
        if SinaUserAccountViewModel.shared.userLogin {
            //注册单元格
            registTheCell()
            
            //行高
            tableView.rowHeight = 350
            //菊花视图
            tableView.tableFooterView = refreshIndicator
            
            //下拉刷新控件
            tableView.addSubview(refView)
            refView.addTarget(self, action: #selector(refreshData), for: .valueChanged)
            
            
            //创建提示还有多少条微博的Lable
            
            self.view.insertSubview(refCountLbl, belowSubview: self.naviBar)
            refCountLbl.backgroundColor = UIColor.orange
            refCountLbl.font = UIFont.systemFont(ofSize: 17)
            refCountLbl.isHidden = true
            refCountLbl.textAlignment = .center
            
            
            //加载数据
            homeViewModel.loadData(isPullUp: false, finished: { (isSuccess,count) in
                if !isSuccess {
                    return
                }
                if !self.refreshIndicator!.isAnimating{
                    self.startAnimtaion(count: count)
                }
                    self.refView.endRefreshing()
                    self.tableView.reloadData()
                    
            })
        }
        
    }
    
    // MARK:
    // MARK: - 提示有多少更新消息动画
    private func startAnimtaion(count: Int) {
        
        if refCountLbl.isHidden == false {
            return
        }
        self.refCountLbl.isHidden = false
        self.refCountLbl.text = (count == 0 ? "没有新微博" : "更新了\(count)条微博")
        
        UIView.animate(withDuration: 1.0, animations: {
            self.refCountLbl.transform = CGAffineTransform.init(translationX: 0, y: 35)
        }, completion: { (res) in
            
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.refCountLbl.transform = CGAffineTransform.identity
            }, completion: { (res) in
                self.refCountLbl.isHidden = true
            })
            
        })

        
    }
    
    
    
    
    // MARK:
    // MARK: - 下拉刷新
    @objc private func refreshData(){
        
        homeViewModel.loadData(isPullUp: false) { (isSuccess, count) in
            if !isSuccess {
                return
            }
            
            if self.refCountLbl.isHidden{
                self.refView.endRefreshing()
                self.tableView.reloadData()
                
                self.refCountLbl.isHidden = false
                self.refCountLbl.text = (count == 0 ? "没有新微博" : "更新了\(count)条微博")
                
                UIView.animate(withDuration: 1.0, animations: {
                    self.refCountLbl.transform = CGAffineTransform.init(translationX: 0, y: 35)
                }, completion: { (res) in
                    
                    UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                        self.refCountLbl.transform = CGAffineTransform.identity
                    }, completion: { (res) in
                        self.refCountLbl.isHidden = true
                    })
                    
                })
            }
            
            
        }
        
    }
    
    
    
    // MARK:
    // MARK: - TableView注册单元格
    func registTheCell() {
        let nib = UINib(nibName: "SinaHomeCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: cellID)
        
        let retweeteNib = UINib(nibName: "SinaHomeReTweeteCell", bundle: nil)
        tableView.register(retweeteNib, forCellReuseIdentifier: retweeteCellID)
    }
    

    
    
    
    
    
    // MARK:
    // MARK: - 如果登录了,把主视图设置为tableView
    override func loadView() {
        super.loadView()
        //如果登录了
        if isLogin{
            view.insertSubview(tableView, belowSubview: naviBar)
            tableView.snp.makeConstraints({ (make) in
                make.edges.equalTo(view)
            })
            tableView.separatorStyle = .none
            tableView.contentOffset = CGPoint(x: 0, y: -44)
            tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
            tableView.delegate = self
            tableView.dataSource = self
        }
    }
    
    
    
    
    
    // MARK:
    // MARK: - 添加右上方按钮
    private func addDemoBtn(){
        
        let btnItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(btnDidClick))
        
        self.naviItem.rightBarButtonItem = btnItem
        
    }
    
    // MARK:
    // MARK: - 点击右方按钮跳转到demo界面
    @objc private func btnDidClick(){
        
        navigationController?.pushViewController(SinaDemoViewController(), animated: true)
        
    }
    

}



extension SinaHomeViewController: UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.statusVMList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var theCellid: String
        
        if homeViewModel.statusVMList[indexPath.row].statusModel?.retweeted_status != nil {
            theCellid = retweeteCellID
        }else{
            theCellid = cellID
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: theCellid, for: indexPath) as! SinaHomeCell
//        cell.contentView.backgroundColor = randomColor()
        cell.homeCellViewModel = homeViewModel.statusVMList[indexPath.row]
        return cell
    }
    
    
    
    // MARK:
    // MARK: - 动态行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = homeViewModel.statusVMList[indexPath.row]
        
        let nibName = getNibName(homeCellViewModel: model)
        
        let nib = UINib(nibName: nibName, bundle: nil)
        
        let cell = nib.instantiate(withOwner: nil, options: nil).last as! SinaHomeCell
        
        cell.homeCellViewModel = model
        cell.layoutIfNeeded()
        
        return cell.rowHeight
        
    }
    
    
    
    
    
    
    // MARK:
    // MARK: - 得到nib名字
    private func getNibName(homeCellViewModel: SinaHomeCellViewModel) -> (String){
        let nibName = homeCellViewModel.statusModel?.retweeted_status == nil ? "SinaHomeCell":"SinaHomeReTweeteCell"
        return nibName
    }
    
    
    // MARK:
    // MARK: - cell将要显示的时候
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if refreshIndicator!.isAnimating == false && indexPath.row == homeViewModel.statusVMList.count - 2 {
            
            //菊花开始转动 数据开始加载
            refreshIndicator?.startAnimating()
            
            homeViewModel.loadData(isPullUp: true, finished: { (isSuccess,count) in
                if !isSuccess {
                    return
                }
                self.refreshIndicator?.stopAnimating()
                self.tableView.reloadData()
            })
            
        }
        
    }
    
    
    
    
    
}
